# -*- coding:utf-8 -*-

__author__='zhaoxp'

import datetime
import time
import json

'''
使用None和文档字符串来描述具有动态默认值的参数
'''

def log(message,when=datetime.datetime.now()):
    '''默认参数只初始化一次'''
    print('%s: %s'%(when,message))

def log2(message,when=None):
    '''默认参数设置为None，然后在函数中赋值'''
    when=datetime.datetime.now() if when is None else when
    print('%s: %s'%(when,message))


def decode_json(data,default={}):
    '''这里的默认参数被初始化为{}，因为默认参数只会被初始化一次，所以这里看到它永远为{}'''
    try:
        return json.loads(data)
    except ValueError:
        return default

def decode_json2(data,default=None):
    '''同样的，默认参数设置为None，然后在函数中赋值'''
    if default is None:
        default={}
    try:
        return json.loads(data)
    except ValueError:
        return default

if __name__=='__main__':
    print('use keyword args')
    # default argument is initialized just once
    log('hi there!')
    print('sleep 0.3')
    time.sleep(0.3)
    log('hi again')
    print('')
    
    print('argument = None')
    log2('hello world')
    time.sleep(0.3)
    log2('good morning')
    print('')
    
    foo=decode_json('bad data')
    bar=decode_json('also bad data')
    foo['hello']='world'
    bar['good']='day'
    print('foo is %s'%foo)
    print('bar is %s'%bar)
    print('foo is bar %s'%(foo is bar))
    print('')
    
    print('reset foo and bar')
    foo=decode_json2('bad data')
    bar=decode_json2('also bad data')
    foo['hello']='world'
    bar['good']='day'
    print('foo is %s'%foo)
    print('bar is %s'%bar)
    print('foo is bar %s'%(foo is bar))
    